package com.example.musicplayer.view;

import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.Scroller;

import com.example.musicplayer.R;

import java.util.LinkedList;
import java.util.Queue;

public class HorizontalListView extends AdapterView<ListAdapter> {
    private static final int CLICK_EVENT_MAX_DISTANCE = 5;
    public boolean mAlwaysOverrideTouch;
    protected ListAdapter mAdapter;
    private int mLeftViewIndex;
    private int mRightViewIndex;
    private int mCurrentX;
    private int mNextX;
    private int mMaxX;
    private int mDisplayOffset;
    private int mStartTouchX;
    private int mStartTouchNextX;
    private boolean mDataChanged;
    private boolean mStillDown;
    private boolean mOnSelectionScroll;
    private int mSelectionPosition;
    private Scroller mScroller;
    private GestureDetector mGestureDetector;
    private OnItemSelectedListener mOnItemSelectedListener;
    private OnItemClickListener mOnItemClickListener;
    private OnItemLongClickListener mOnItemLongClickListener;
    private Queue<View> mRemovedQueue;

    public HorizontalListView(Context context) {
        this(context, null);
    }

    public HorizontalListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    @Override
    public ListAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public void setAdapter(ListAdapter adapter) {
        if (mAdapter != null) {
            mAdapter.unregisterDataSetObserver(mDataSetObserver);
        }
        mAdapter = adapter;
        if (mAdapter != null) {
            mAdapter.registerDataSetObserver(mDataSetObserver);
        }
        reset();
    }

    @Override
    public View getSelectedView() {
        return null;
    }

    @Override
    public void setSelection(int position) {
        if (mAdapter != null && position >= 0 && position < mAdapter.getCount()) {
            mOnSelectionScroll = true;
            mSelectionPosition = position;
            int width = getChildAt(0).getWidth();
            mScroller.startScroll(mNextX, 0, (position - mLeftViewIndex - 1) * width + mDisplayOffset
                    , 0, 10);
            requestLayout();
        }
    }

    @Override
    public void setOnItemSelectedListener(OnItemSelectedListener onItemSelectedListener) {
        mOnItemSelectedListener = onItemSelectedListener;
    }

    @Override
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    @Override
    public void setOnItemLongClickListener(OnItemLongClickListener onItemLongClickListener) {
        mOnItemLongClickListener = onItemLongClickListener;
        mGestureDetector.setIsLongpressEnabled(mOnItemLongClickListener != null);
    }

    public synchronized void scrollTo(int x) {
        mScroller.startScroll(mNextX, 0, x - mNextX, 0, 500);
        requestLayout();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        boolean handled = super.dispatchTouchEvent(ev);
        handled |= mGestureDetector.onTouchEvent(ev);
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            mStillDown = true;
        } else if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
            mStillDown = false;
            requestLayout();
        }
        return handled;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mStartTouchX = (int) ev.getX();
                mStartTouchNextX = mNextX;
                break;
            case MotionEvent.ACTION_MOVE:
            case MotionEvent.ACTION_UP:
                //the conflict between click and scroll
                int dx = (int) (ev.getX() - mStartTouchX);
                if (Math.abs(dx) > CLICK_EVENT_MAX_DISTANCE) {
                    return true;
                }
                break;
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    protected synchronized void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (mAdapter == null) {
            return;
        }
        if (mDataChanged) {
            mDataChanged = false;
            updateChildView();
        }
        if (mScroller.computeScrollOffset()) {
            mNextX = mScroller.getCurrX();
        }
        if (mStillDown) {
            if (mNextX < 0) {
                mNextX = (int) (-Math.pow(-mNextX, 0.9));
            } else if (mNextX > mMaxX) {
                mNextX = (int) (mMaxX + Math.pow(mNextX - mMaxX, 0.9));
            }
        } else {
            if (mNextX < 0) {
                mNextX = 0;
                mScroller.forceFinished(true);
            }
            if (mNextX > mMaxX) {
                mNextX = mMaxX;
                mScroller.forceFinished(true);
            }
        }
        int dx = mCurrentX - mNextX;
        removeNonVisibleItems(dx);
        fillList(dx);
        positionItems(dx);
        mCurrentX = mNextX;
        if (!mScroller.isFinished()) {
            post(new Runnable() {
                @Override
                public void run() {
                    requestLayout();
                }
            });
        }
    }

    protected boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        synchronized (HorizontalListView.this) {
            mScroller.fling(mNextX, 0, (int) (-velocityX * 1.3f), 0,
                    Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0);
        }
        requestLayout();
        return true;
    }

    protected boolean onDown(MotionEvent e) {
        mScroller.forceFinished(true);
        return true;
    }

    private synchronized void initView() {
        mAlwaysOverrideTouch = true;
        mLeftViewIndex = -1;
        mRightViewIndex = 0;
        mCurrentX = 0;
        mNextX = 0;
        mMaxX = Integer.MAX_VALUE;
        mDisplayOffset = 0;
        mDataChanged = false;
        mStillDown = false;
        mOnSelectionScroll = false;
        mSelectionPosition = -1;
        mScroller = new Scroller(getContext());
        mGestureDetector = new GestureDetector(getContext(), mOnGestureListener);
        mRemovedQueue = new LinkedList<View>();
        mGestureDetector.setIsLongpressEnabled(false);
    }

    private synchronized void reset() {
        initView();
        removeAllViewsInLayout();
        requestLayout();
    }

    private void addChildAndMeasure(View child, int position) {
        //set background if not
        if (child.getBackground() == null) {
            child.setBackgroundResource(R.drawable.ripple_horizontal_listview_item_default);
            child.setFocusable(true);
            child.setClickable(true);
        }
        LayoutParams lp = child.getLayoutParams();
        if (lp == null) {
            lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        }
        int widthSize = lp.width > 0 ? lp.width : getWidth();
        int heightSize = lp.height > 0 ? lp.height : getHeight();
        addViewInLayout(child, position, lp, true);
        child.measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY),
                MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY));
    }

    private void updateChildView() {
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            if (child != null) {
                mAdapter.getView(mLeftViewIndex + 1 + i, child, this);
            }
        }
    }

    private void fillList(final int dx) {
        int edge = 0;
        View child = getChildAt(getChildCount() - 1);
        if (child != null) {
            edge = child.getRight();
        }
        fillListRight(edge, dx);
        edge = 0;
        child = getChildAt(0);
        if (child != null) {
            edge = child.getLeft();
        }
        fillListLeft(edge, dx);
    }

    private void fillListLeft(int leftEdge, final int dx) {
        while (leftEdge + dx > 0 && mLeftViewIndex >= 0) {
            View child = mAdapter.getView(mLeftViewIndex, mRemovedQueue.poll(), this);
            addChildAndMeasure(child, 0);
            leftEdge -= child.getMeasuredWidth();
            mLeftViewIndex--;
            mDisplayOffset -= child.getMeasuredWidth();
        }
    }

    private void fillListRight(int rightEdge, final int dx) {
        while (rightEdge + dx < getWidth() && mRightViewIndex < mAdapter.getCount()) {
            View child = mAdapter.getView(mRightViewIndex, mRemovedQueue.poll(), this);
            addChildAndMeasure(child, -1);
            rightEdge += child.getMeasuredWidth();
            if (mRightViewIndex == mAdapter.getCount() - 1) {
                mMaxX = mCurrentX + rightEdge - getWidth();
            }
            if (mMaxX < 0) {
                mMaxX = 0;
            }
            mRightViewIndex++;
        }
    }

    private void removeNonVisibleItems(final int dx) {
        View child = getChildAt(0);
        while (child != null && child.getRight() + dx <= 0) {
            mDisplayOffset += child.getMeasuredWidth();
            mRemovedQueue.offer(child);
            removeViewInLayout(child);
            mLeftViewIndex++;
            child = getChildAt(0);
        }
        child = getChildAt(getChildCount() - 1);
        while (child != null && child.getLeft() + dx >= getWidth()) {
            mRemovedQueue.offer(child);
            removeViewInLayout(child);
            mRightViewIndex--;
            child = getChildAt(getChildCount() - 1);
        }
    }

    private void positionItems(final int dx) {
        if (getChildCount() > 0) {
            mDisplayOffset += dx;
            int left = mDisplayOffset;
            for (int i = 0; i < getChildCount(); i++) {
                View child = getChildAt(i);
                int childWidth = child.getMeasuredWidth();
                child.layout(left, 0, left + childWidth, child.getMeasuredHeight());
                left += childWidth + child.getPaddingRight();
            }
        }
    }

    private final DataSetObserver mDataSetObserver = new DataSetObserver() {

        @Override
        public void onChanged() {
            synchronized (HorizontalListView.this) {
                mDataChanged = true;
            }
            invalidate();
            requestLayout();
        }

        @Override
        public void onInvalidated() {
            reset();
            invalidate();
            requestLayout();
        }
    };

    private final GestureDetector.OnGestureListener mOnGestureListener = new GestureDetector.SimpleOnGestureListener() {

        @Override
        public boolean onDown(MotionEvent e) {
            return HorizontalListView.this.onDown(e);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return HorizontalListView.this.onFling(e1, e2, velocityX, velocityY);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            //limit the distance
            if (Math.abs(e1.getX() - e2.getX()) <= CLICK_EVENT_MAX_DISTANCE) {
                return false;
            }
            synchronized (HorizontalListView.this) {
                //mNextX += (int) distanceX;
                mNextX = (int) (e1.getX() - e2.getX() + mStartTouchNextX);
            }
            requestLayout();
            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            for (int i = 0; i < getChildCount(); i++) {
                View child = getChildAt(i);
                if (isEventWithinView(e, child)) {
                    if (mOnItemClickListener != null) {
                        mOnItemClickListener.onItemClick(HorizontalListView.this, child
                                , mLeftViewIndex + 1 + i, mAdapter.getItemId(mLeftViewIndex + 1 + i));
                    }
                    if (mOnItemSelectedListener != null) {
                        mOnItemSelectedListener.onItemSelected(HorizontalListView.this, child
                                , mLeftViewIndex + 1 + i, mAdapter.getItemId(mLeftViewIndex + 1 + i));
                    }
                    break;
                }
            }
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            for (int i = 0; i < getChildCount(); i++) {
                View child = getChildAt(i);
                if (isEventWithinView(e, child)) {
                    if (mOnItemLongClickListener != null) {
                        mOnItemLongClickListener.onItemLongClick(HorizontalListView.this, child
                                , mLeftViewIndex + 1 + i, mAdapter.getItemId(mLeftViewIndex + 1 + i));
                    }
                    break;
                }
            }
        }

        private boolean isEventWithinView(MotionEvent e, View child) {
            Rect viewRect = new Rect();
            int[] childViewPosition = new int[2];
            child.getLocationOnScreen(childViewPosition);
            viewRect.set(childViewPosition[0], childViewPosition[1], childViewPosition[0] + child.getWidth()
                    , childViewPosition[1] + child.getHeight());
            return viewRect.contains((int) e.getRawX(), (int) e.getRawY());
        }
    };
}